package com.zy_demo.wxapi;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zygame.sdk.ConstantValue;
import com.zygame.sdk.ZyGameSDK;
import com.zygame.sdk.model.UserModel;
import com.zygame.sdk.utils.LoginUtil;
import com.zygame.sdk.utils.SharedPreferencesHelper;
import com.zygame.sdk.utils.http.HttpUtil;
import com.zygame.sdk.utils.http.NetHttpUtil;
import com.zygame.sdk.utils.log.LogHelper;
import com.zygame.sdk.utils.toast.ToastUtil;
import com.zygame.sdk.view.dialog.Zy_Dialog_main;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by YuXL on 2017/11/2.
 */

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private Context context;
    private String code;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String zy_gmail = SharedPreferencesHelper.getInstance().getWechat(context);
            HttpUtil.login("", "", "",zy_gmail, result1, context, onLoginCallback);
        }
    };
    private String result1;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("加载中，请稍候...");
        progressDialog.show();
        IWXAPI api = WXAPIFactory.createWXAPI(this, ConstantValue.APP_ID, true);
        api.registerApp(ConstantValue.APP_ID);
        api.handleIntent(getIntent(), this);
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp resp) {
        int result = 0;

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
//                result = R.string.errcode_success;
                SendAuth.Resp resp1 = (SendAuth.Resp) resp;
                code = ((SendAuth.Resp) resp).code;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String urlstr = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ConstantValue.APP_ID+"&secret="+ ConstantValue.APP_key+"&code="+ code +"&grant_type=authorization_code";
                            URL url = new URL(urlstr);
                            HttpURLConnection conn = null;
                            conn = (HttpURLConnection) url.openConnection();
                            conn.setConnectTimeout(300000);
                            conn.setDoInput(true); // 允许输入流
                            conn.setDoOutput(true); // 允许输出流
                            conn.setUseCaches(false); // 不允许使用缓存
                            conn.setRequestMethod("GET"); // 请求方式
                            conn.setRequestProperty("Charset", "UTF-8"); // 设置编码
                            conn.connect();
                            int res = conn.getResponseCode();
                            if (res == 200) {
                                result1 = "";
                                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                                String line = "";
                                while ((line = reader.readLine()) != null) {
                                    result1 += line;
                                }
                                reader.close();

                                mHandler.sendEmptyMessage(0);
                                LogHelper.i("ht.resultCallback","返回"+ result1);

                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                break;
//            case BaseResp.ErrCode.ERR_USER_CANCEL:
//                result = R.string.errcode_cancel;
//                break;
//            case BaseResp.ErrCode.ERR_AUTH_DENIED:
//                result = R.string.errcode_deny;
//                break;
//            case BaseResp.ErrCode.ERR_UNSUPPORT:
//                result = R.string.errcode_unsupported;
//                break;
            default:
                ToastUtil.showToast(WXEntryActivity.this,"微信登录失败");
                progressDialog.dismiss();
                finish();
                break;
        }

    }

    NetHttpUtil.DataCallback<JSONObject> onLoginCallback = new NetHttpUtil.DataCallback<JSONObject>() {

        @Override
        public void callbackSuccess(JSONObject paramObject) {
            LogHelper.i("login接口", paramObject.toString());
            String code = paramObject.optString("code");

            if (code.equals("0")) {
                String user_name = paramObject.optString("user_name");
                LoginUtil.loginResult(user_name, user_name, paramObject, context,SharedPreferencesHelper.getInstance().getWechat(context),1,result1);
                ZyGameSDK.getInstance().onLoginResult(UserModel.getInstance());
//                if(ZyGameSDK.getInstance().login != null ){
//                    ZyGameSDK.getInstance().login.dissDialog();
//                }
                Zy_Dialog_main.getInstance(context).dissDialog();

            } else {

                ToastUtil.showToast(WXEntryActivity.this,paramObject.optString("message"));
            }
            progressDialog.dismiss();
            finish();
        }

        @Override
        public void callbackError(String error) {
            LogHelper.i("login接口", error);
            ToastUtil.showToast(WXEntryActivity.this,"微信登录失败");
            progressDialog.dismiss();
            finish();
        }
    };
}
